/*
 * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package jsr203.nio.file.attribute;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import jsr203.nio.file.FileRef;
import jsr203.nio.file.FileStore;

/**
 * Utility and helper methods to access file and file system attributes.
 *
 * @since 1.7
 */

public final class Attributes {
    private Attributes() {
    }

    /**
     * Reads the basic file attributes of the given file.
     *
     * <p> It is implementation specific if all file attributes are read as an
     * atomic operation with respect to other file system operations.
     *
     * <p> The {@code followLinks} indicates if the symbolic links should be
     * followed. When the value of this parameter is {@code false}, and the
     * file is a link, then this method reads the attributes of the link. This
     * parameter is ignored by implementations that do not support symbolic links.
     *
     * @param   file
     *          A file reference that locates the file
     * @param   followLinks
     *          {@code true} to follow symbolic links; {@code false} otherwise
     *
     * @return  The basic file attributes
     *
     * @throws  IOException
     *          If an I/O error occurs
     * @throws  SecurityException
     *          In the case of the default provider, the security manager's {@link
     *          SecurityManager#checkRead(String) checkRead} method is invoked
     *          to check read access to file
     *
     * @see BasicFileAttributeView#readAttributes
     */
    public static BasicFileAttributes readBasicFileAttributes(FileRef file,
                                                              boolean followLinks)
        throws IOException
    {
        return file.newFileAttributeView(BasicFileAttributeView.class, followLinks)
            .readAttributes();
    }

    /**
     * Reads the POSIX file attributes of the given file.
     *
     * <p> The {@code file} parameter is a file reference to locate the file.
     * It supports the {@link PosixFileAttributeView} that provides access to a
     * subset of the file attributes commonly associated with files on file
     * systems used by operating systems that implement the Portable Operating
     * System Interface (POSIX) family of standards. It is implementation
     * specific if all file attributes are read as an atomic operation with
     * respect to other file system operations.
     *
     * <p> The {@code followLinks} indicates if the symbolic links should be
     * followed. When the value of this parameter is {@code false}, and the
     * file is a link, then this method reads the attributes of the link. This
     * parameter is ignored by implementations that do not support symbolic links.
     *
     * @param   file
     *          A file reference that locates the file
     * @param   followLinks
     *          {@code true} to follow symbolic links; {@code false} otherwise
     *
     * @return  The POSIX file attributes
     *
     * @throws  UnsupportedOperationException
     *          If the {@code PosixFileAttributeView} is not available, or if
     *          not following links, the file is a link, and the implementation
     *          does not support reading the attributes of a symbolic link
     * @throws  IOException
     *          If an I/O error occurs
     * @throws  SecurityException
     *          In the case of the default provider, and a security manager is
     *          installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt>
     *          or its {@link SecurityManager#checkRead(String) checkRead} method
     *          denies read access to the file.
     *
     * @see PosixFileAttributeView#readAttributes
     */
    public static PosixFileAttributes readPosixFileAttributes(FileRef file,
                                                              boolean followLinks)
        throws IOException
    {
        PosixFileAttributeView view =
            file.newFileAttributeView(PosixFileAttributeView.class, followLinks);
        if (view == null)
            throw new UnsupportedOperationException();
        return view.readAttributes();
    }

    /**
     * Reads the DOS file attributes of the given file.
     *
     * <p> The {@code file} parameter is a file reference to locate the file.
     * It supports the {@link DosFileAttributeView} that provides access to
     * legacy "DOS" attributes supported by the file systems such as File
     * Allocation Table (FAT), commonly used in <em>consumer devices</em>.
     *
     * <p> The {@code followLinks} indicates if the symbolic links should be
     * followed. When the value of this parameter is {@code false}, and the
     * file is a link, then this method reads the attributes of the link. This
     * parameter is ignored by implementations that do not support symbolic links.
     *
     * @param   file
     *          A file reference that locates the file
     * @param   followLinks
     *          {@code true} to follow symbolic links; {@code false} otherwise
     *
     * @return  The DOS file attributes
     *
     * @throws  UnsupportedOperationException
     *          If the {@code DosFileAttributeView} is not available, or if
     *          not following links, the file is a link, and the implementation
     *          does not support reading the attributes of a symbolic link
     * @throws  IOException
     *          If an I/O error occurs
     * @throws  SecurityException
     *          In the case of the default provider, the security manager's {@link
     *          SecurityManager#checkRead(String) checkRead} method is invoked
     *          to check read access to file
     *
     * @see DosFileAttributeView#readAttributes
     */
    public static DosFileAttributes readDosFileAttributes(FileRef file,
                                                          boolean followLinks)
        throws IOException
    {
        DosFileAttributeView view =
            file.newFileAttributeView(DosFileAttributeView.class, followLinks);
        if (view == null)
            throw new UnsupportedOperationException();
        return view.readAttributes();
    }

    /**
     * Returns the owner of the given file.
     *
     * <p> The {@code file} parameter is a file reference to locate the file. It
     * supports the {@link FileOwnerAttributeView} that provides access to the
     * file attribute that is the owner of the file.
     *
     * @param   file
     *          A file reference that locates the file
     *
     * @return  A user principal representing the owner of the file
     *
     * @throws  UnsupportedOperationException
     *          If the {@code FileOwnerAttributeView} is not available
     * @throws  IOException
     *          If an I/O error occurs
     * @throws  SecurityException
     *          In the case of the default provider, and a security manager is
     *          installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt>
     *          or its {@link SecurityManager#checkRead(String) checkRead} method
     *          denies read access to the file.
     *
     * @see FileOwnerAttributeView#getOwner
     */
    public static UserPrincipal getOwner(FileRef file) throws IOException {
        FileOwnerAttributeView view =
            file.newFileAttributeView(FileOwnerAttributeView.class, true);
        if (view == null)
            throw new UnsupportedOperationException();
        return view.getOwner();
    }

    /**
     * Updates the file owner.
     *
     * <p> The {@code file} parameter is a file reference to locate the file. It
     * supports the {@link FileOwnerAttributeView} that provides access to the
     * file attribute that is the owner of the file.
     *
     * @param   file
     *          A file reference that locates the file
     * @param   owner
     *          The new file owner
     *
     * @throws  IOException
     *          If an I/O error occurs
     * @throws  SecurityException
     *          In the case of the default provider, and a security manager is
     *          installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt>
     *          or its {@link SecurityManager#checkWrite(String) checkWrite}
     *          method denies write access to the file.
     *
     * @see FileOwnerAttributeView#setOwner
     */
    public static void setOwner(FileRef file, UserPrincipal owner)
            throws IOException
    {
        FileOwnerAttributeView view =
            file.newFileAttributeView(FileOwnerAttributeView.class, true);
        if (view != null)
            view.setOwner(owner);
    }

    /**
     * Updates the value of a file's last modified time attribute.
     *
     * <p> The time value is measured since the epoch
     * (00:00:00 GMT, January 1, 1970) and is converted to the precision supported
     * by the file system. Converting from finer to coarser granularities result
     * in precision loss.
     *
     * @param   file
     *          A file reference that locates the file
     *
     * @param   lastModifiedTime
     *          The new last modified time, or {@code -1L} to update it to
     *          the current time
     * @param   unit
     *          A {@code TimeUnit} determining how to interpret the
     *          {@code lastModifiedTime} parameter
     *
     * @throws  IllegalArgumentException
     *          If the {@code lastModifiedime} parameter is a negative value other
     *          than {@code -1L}
     * @throws  IOException
     *          If an I/O error occurs
     * @throws  SecurityException
     *          In the case of the default provider, the security manager's {@link
     *          SecurityManager#checkWrite(String) checkWrite} method is invoked
     *          to check write access to file
     *
     * @see BasicFileAttributeView#setTimes
     */
    public static void setLastModifiedTime(FileRef file,
                                           long lastModifiedTime,
                                           TimeUnit unit)
        throws IOException
    {
        file.newFileAttributeView(BasicFileAttributeView.class, true)
            .setTimes(lastModifiedTime, null, null, unit);
    }

    /**
     * Updates the value of a file's last access time attribute.
     *
     * <p> The time value is measured since the epoch
     * (00:00:00 GMT, January 1, 1970) and is converted to the precision supported
     * by the file system. Converting from finer to coarser granularities result
     * in precision loss.
     *
     * <p> If the file system does not support a last access time attribute then
     * this method has no effect.
     *
     * @param   lastAccessTime
     *          The new last access time, or {@code -1L} to update it to
     *          the current time
     * @param   unit
     *          A {@code TimeUnit} determining how to interpret the
     *          {@code lastModifiedTime} parameter
     *
     * @throws  IllegalArgumentException
     *          If the {@code lastAccessTime} parameter is a negative value other
     *          than {@code -1L}
     * @throws  IOException
     *          If an I/O error occurs
     * @throws  SecurityException
     *          In the case of the default provider, the security manager's {@link
     *          SecurityManager#checkWrite(String) checkWrite} method is invoked
     *          to check write access to file
     *
     * @see BasicFileAttributeView#setTimes
     */
    public static void setLastAccessTime(FileRef file,
                                         long lastAccessTime,
                                         TimeUnit unit)
        throws IOException
    {
        file.newFileAttributeView(BasicFileAttributeView.class, true)
            .setTimes(null, lastAccessTime, null, unit);
    }

    /**
     * Updates the value of a file's creation time attribute.
     *
     * <p> The time value is measured since the epoch
     * (00:00:00 GMT, January 1, 1970) and is converted to the precision supported
     * by the file system. Converting from finer to coarser granularities result
     * in precision loss.
     *
     * <p> If the file system does not support a file creation time attribute
     * then this method has no effect.
     *
     * @param   createTime
     *          The new create time, or {@code -1L} to update it to
     *          the current time
     * @param   unit
     *          A {@code TimeUnit} determining how to interpret the
     *          {@code createTime} parameter
     *
     * @throws  IllegalArgumentException
     *          If the {@code createTime} parameter is a negative value other
     *          than {@code -1L}
     * @throws  IOException
     *          If an I/O error occurs
     * @throws  SecurityException
     *          In the case of the default provider, the security manager's {@link
     *          SecurityManager#checkWrite(String) checkWrite} method is invoked
     *          to check write access to file
     *
     * @see BasicFileAttributeView#setTimes
     */
    public static void setCreationTime(FileRef file,
                                       long createTime,
                                       TimeUnit unit)
        throws IOException
    {
        file.newFileAttributeView(BasicFileAttributeView.class, true)
            .setTimes(null, null, createTime, unit);
    }

    /**
     * Updates the POSIX file permissions of the given file.
     *
     * <p> The {@code file} parameter is a file reference to locate the file.
     * If the {@link PosixFileAttributeView} is supported, then this method
     * updates the file's permissions. If this file attribute view is not
     * supported then this method has no effect.
     *
     * @param   file
     *          A file reference that locates the file
     * @param   perms
     *          The new set of permissions
     *
     * @throws  ClassCastException
     *          If the sets contains elements that are not of type {@code
     *          PosixFilePermission}
     * @throws  IOException
     *          If an I/O error occurs
     * @throws  SecurityException
     *          In the case of the default provider, and a security manager is
     *          installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt>
     *          or its {@link SecurityManager#checkWrite(String) checkWrite}
     *          method denies write access to the file.
     *
     * @see PosixFileAttributeView#setPermissions
     */
    public static void setPosixFilePermissions(FileRef file,
                                               Set<PosixFilePermission> perms)
        throws IOException
    {
        PosixFileAttributeView view =
            file.newFileAttributeView(PosixFileAttributeView.class, true);
        if (view != null)
            view.setPermissions(perms);
    }

    /**
     * Updates the POSIX file permissions of the given file.
     *
     * <p> The {@code file} parameter is a file reference to locate the file.
     * If the {@link PosixFileAttributeView} is supported, then this method
     * updates the file's permissions. If this file attribute view is not
     * supported then this method has no effect.
     *
     * @param   file
     *          A file reference that locates the file
     * @param   perms
     *          Optional array with the new permissions
     *
     * @throws  IOException
     *          If an I/O error occurs
     * @throws  SecurityException
     *          In the case of the default provider, and a security manager is
     *          installed, it denies {@link RuntimePermission}<tt>("accessUserInformation")</tt>
     *          or its {@link SecurityManager#checkWrite(String) checkWrite}
     *          method denies write access to the file.
     *
     * @see PosixFileAttributeView#setPermissions
     */
    public static void setPosixFilePermissions(FileRef file,
                                               PosixFilePermission... perms)
        throws IOException
    {
        PosixFileAttributeView view =
            file.newFileAttributeView(PosixFileAttributeView.class, true);
        if (view != null) {
            Set<PosixFilePermission> set =
                new HashSet<PosixFilePermission>(perms.length);
            Collections.addAll(set, perms);
            view.setPermissions(set);
        }
    }

    /**
     * Reads the space attributes of a file store.
     *
     * <p> The {@code fs} parameter is a file store that supports the
     * {@link FileStoreSpaceAttributeView} providing access to the space related
     * attributes of the file store. It is implementation specific if all attributes
     * are read as an atomic operation with respect to other file system operations.
     *
     * @param   fs
     *          The file store
     *
     * @return  The file store space attributes
     *
     * @throws  UnsupportedOperationException
     *          If the file store space attribute view is not supported
     * @throws  IOException
     *          If an I/O error occurs
     * @throws  SecurityException
     *          In the case of the default provider, and a security manager is
     *          installed, its {@link SecurityManager#checkRead(String) checkRead}
     *          method is invoked to check read access to the file used to {@link
     *          FileRef#getFileStore obtain} access to the file
     *          store, and in addition it checks {@link RuntimePermission}<tt>
     *          ("getFileStoreAttributes")</tt>
     */
    public static FileStoreSpaceAttributes readFileStoreSpaceAttributes(FileStore fs)
        throws IOException
    {
        FileStoreSpaceAttributeView view =
            fs.newFileStoreAttributeView(FileStoreSpaceAttributeView.class);
        if (view == null)
            throw new UnsupportedOperationException();
        return view.readAttributes();
    }
}
